#!/usr/bin/env python3

import os
import pathlib
import sys
import zipfile

import requests

ROOT_DIR = ".."
DIST_DIR = "dist"
USER_REPO = "kitao/pyxel"
WORKFLOW_NAME = "build-wasm"
GITHUB_TOKEN = os.environ.get("GITHUB_TOKEN")


def get_workflow_id():
    url = f"https://api.github.com/repos/{USER_REPO}/actions/workflows"
    headers = {"Authorization": f"token {GITHUB_TOKEN}"}
    response = requests.get(url, headers=headers)
    workflows = response.json()

    for workflow in workflows.get("workflows", []):
        if workflow["name"] == WORKFLOW_NAME:
            return workflow["id"]

    print("workflow not found")
    sys.exit(1)


def get_latest_run_id(workflow_id):
    url = (
        f"https://api.github.com/repos/{USER_REPO}/actions/workflows/{workflow_id}/runs"
    )
    headers = {"Authorization": f"token {GITHUB_TOKEN}"}
    response = requests.get(url, headers=headers)
    runs = response.json()

    if not runs.get("workflow_runs"):
        print("workflow runs not found")
        sys.exit(1)

    return runs["workflow_runs"][0]["id"]


def get_artifact_info(latest_run_id):
    url = f"https://api.github.com/repos/{USER_REPO}/actions/runs/{latest_run_id}/artifacts"
    headers = {"Authorization": f"token {GITHUB_TOKEN}"}
    response = requests.get(url, headers=headers)
    artifacts = response.json()

    if not artifacts.get("artifacts"):
        print("artifacts not found")
        sys.exit(1)

    return artifacts["artifacts"][0]


def download_and_extract_artifact(artifact_info):
    artifact_name = artifact_info["name"]
    artifact_url = artifact_info["archive_download_url"]
    headers = {"Authorization": f"token {GITHUB_TOKEN}"}
    download_response = requests.get(artifact_url, headers=headers)

    zip_file_path = os.path.join(DIST_DIR, f"{artifact_name}.zip")
    os.makedirs(DIST_DIR, exist_ok=True)

    with open(zip_file_path, "wb") as file:
        file.write(download_response.content)

    with zipfile.ZipFile(zip_file_path, "r") as zip_ref:
        zip_ref.extractall(DIST_DIR)

    os.remove(zip_file_path)


def download_wasm_wheel():
    os.chdir(pathlib.Path(__file__).parent / ROOT_DIR)

    workflow_id = get_workflow_id()
    latest_run_id = get_latest_run_id(workflow_id)
    artifact_info = get_artifact_info(latest_run_id)

    download_and_extract_artifact(artifact_info)


if __name__ == "__main__":
    download_wasm_wheel()
